package name.vaccari.matteo.tai.phonedirectory.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class HttpProtocol implements Protocol {

	private final Servlet servlet;

	public HttpProtocol(Servlet servlet) {
		this.servlet = servlet;
	}	

	public void process(InputStream is, OutputStream os) throws IOException {
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		PrintWriter writer = new PrintWriter(os);

		String path = parsePath(reader);
		String body = servlet.doGet(path);
		
		writer.print("HTTP/1.1 200 OK\r\n");
		writer.print("Content-Length: " + body.length() + "\r\n");
		writer.print("Content-Type: text/html\r\n");
		writer.print("\r\n");
		writer.print(body);
		writer.flush();
	}

	private String parsePath(BufferedReader reader) throws IOException {
		String firstLine = reader.readLine();
		String path = firstLine.split(" ")[1];
		return path;
	}

}
